package com.ruoyi.zhgd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.zhgd.util.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.zhgd.domain.ZjTensionReportEdit;
import com.ruoyi.zhgd.mapper.ZjBasicReportMapper;
import com.ruoyi.zhgd.mapper.ZjTensionReportEditMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.zhgd.domain.bo.TensionRecordingBo;
import com.ruoyi.zhgd.domain.vo.TensionRecordingVo;
import com.ruoyi.zhgd.domain.TensionRecording;
import com.ruoyi.zhgd.mapper.TensionRecordingMapper;
import com.ruoyi.zhgd.service.ITensionRecordingService;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 张拉记录Service业务层处理
 *
 * @author zyb
 * @date 2023-09-11
 */
@RequiredArgsConstructor
@Service
@DS("sjcj")
public class TensionRecordingServiceImpl implements ITensionRecordingService {

    private final TensionRecordingMapper baseMapper;

    private final ZjBasicReportMapper zjBasicReportMapper;

    private final ZjTensionReportEditMapper zjTensionReportEditMapper;

    /**
     * 查询张拉记录
     */
    @Override
    public TensionRecordingVo queryById(String id){
        return baseMapper.queryById(id);
    }

    /**
     * 查询张拉记录列表
     */
    @Override
    public TableDataInfo<TensionRecordingVo> queryPageList(TensionRecordingBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TensionRecording> lqw = buildQueryWrapper(bo);
        Page<TensionRecordingVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询张拉记录列表
     */
    @Override
    public List<TensionRecordingVo> queryList(TensionRecordingBo bo) {
        LambdaQueryWrapper<TensionRecording> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TensionRecording> buildQueryWrapper(TensionRecordingBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TensionRecording> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), TensionRecording::getCode, bo.getCode());
        lqw.eq(StringUtils.isNotBlank(bo.getBeamType()), TensionRecording::getBeamType, bo.getBeamType());
        lqw.eq(StringUtils.isNotBlank(bo.getBeamNo()), TensionRecording::getBeamNo, bo.getBeamNo());
        lqw.eq(StringUtils.isNotBlank(bo.getStake()), TensionRecording::getStake, bo.getStake());
        lqw.eq(bo.getTensionTime() != null, TensionRecording::getTensionTime, bo.getTensionTime());
        lqw.eq(StringUtils.isNotBlank(bo.getTensionUser()), TensionRecording::getTensionUser, bo.getTensionUser());
        lqw.eq(bo.getDeflectionUpwards() != null, TensionRecording::getDeflectionUpwards, bo.getDeflectionUpwards());
        lqw.eq(bo.getConcreteDesign() != null, TensionRecording::getConcreteDesign, bo.getConcreteDesign());
        lqw.eq(bo.getConcreteStrength() != null, TensionRecording::getConcreteStrength, bo.getConcreteStrength());
        lqw.eq(bo.getLoadingSpeed() != null, TensionRecording::getLoadingSpeed, bo.getLoadingSpeed());
        lqw.eq(bo.getTensileStress() != null, TensionRecording::getTensileStress, bo.getTensileStress());
        return lqw;
    }

    /**
     * 新增张拉记录
     */
    @Override
    public Boolean insertByBo(TensionRecordingBo bo) {
        TensionRecording add = BeanUtil.toBean(bo, TensionRecording.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改张拉记录
     */
    @Override
    public Boolean updateByBo(TensionRecordingBo bo) {
        TensionRecording update = BeanUtil.toBean(bo, TensionRecording.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TensionRecording entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除张拉记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public PageUtils tensionList(Page page, Map<String, Object> params) {
        List<Map> tensionList = baseMapper.tensionList(page, params);
        return new PageUtils(page.setRecords(tensionList));
    }

    /**
     * 张拉报表基础信息
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> listMap(Map<String, Object> params) {
        if (ObjectUtils.isEmpty(params.get("id"))) {
            throw new ServiceException("主键ID不能为空");
        }
        // 获取通用接口数据
//        List<Map<String, Object>> list = zjBasicReportMapper.listMap(params);
        String bankVal = "";
        // 根据部门信息获取项目信息 合同信息
        Map<String, Object> projectInfo = new HashMap<>();
        TensionRecordingVo project = baseMapper.getProjectById(params);
        if (ObjectUtils.isNotEmpty(project)) {
            projectInfo.put("beamNo", project.getBeamNo());
            projectInfo.put("bridgeName", project.getStake());
            projectInfo.put("projectId", project.getProjectId());
            projectInfo.put("projectName", project.getProjectName());
            projectInfo.put("contractId", project.getContractId());
            projectInfo.put("contractNum", project.getContractNum());
            projectInfo.put("sgGroup", project.getSgGroup());
            projectInfo.put("jlGroup", project.getJlGroup());
        } else {
            projectInfo.put("beamNo", bankVal);
            projectInfo.put("bridgeName", bankVal);
            projectInfo.put("projectId", bankVal);
            projectInfo.put("projectName", bankVal);
            projectInfo.put("contractId", bankVal);
            projectInfo.put("contractNum", bankVal);
            projectInfo.put("sgGroup", bankVal);
            projectInfo.put("jlGroup", bankVal);
        }
        // 获取张拉日期(同一梁号的最新日期),设计砼强度,张拉砼强度,设计伸长值,控制应力(设计张力)
        List<TensionRecordingVo> data = baseMapper.getReportBasicDataByBeamNo(project.getBeamNo());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String zjDef = "基本要求检查符合规定，经自检，检查项目符合规范及设计要求";
        String jlDef = "符合规范及设计要求";

        if (CollectionUtils.isNotEmpty(data)) {
            TensionRecordingVo vo = data.get(0);
            projectInfo.put("tensionTime", sdf.format(vo.getTensionTime()));
            projectInfo.put("concreteDesign", vo.getConcreteDesign());
            projectInfo.put("concreteStrength", vo.getConcreteStrength());
            projectInfo.put("designTension", vo.getDesignTension());
            projectInfo.put("designExtension", vo.getDesignExtension());
            // 新加字段
            projectInfo.put("jackCode1", vo.getJackCode1()); // 1#张拉千斤顶编号
            projectInfo.put("jackCode2", vo.getJackCode2()); // 2#张拉千斤顶编号
            projectInfo.put("sensorCode1", vo.getSensorCode1()); // 1#传感器编号
            projectInfo.put("sensorCode2", vo.getSensorCode2()); // 2#传感器编号

            if (ObjectUtils.isEmpty(vo.getZjComments())) {
                projectInfo.put("zjComments", zjDef); // 自检评语
            } else {
                projectInfo.put("zjComments", vo.getZjComments()); // 自检评语
            }

            if (ObjectUtils.isEmpty(vo.getJlComments())) {
                projectInfo.put("jlComments", jlDef); // 监理评语
            } else {
                projectInfo.put("jlComments", vo.getJlComments()); // 监理评语
            }
            if (ObjectUtils.isEmpty(vo.getZjRq())) {
                projectInfo.put("zjRq", sdf.format(vo.getTensionTime())); // 自检日期
            } else {
                projectInfo.put("zjRq", vo.getZjRq()); // 自检日期
            }
            if (ObjectUtils.isEmpty(vo.getJlRq())) {
                projectInfo.put("jlRq", sdf.format(vo.getTensionTime())); // 监理日期
            } else {
                projectInfo.put("jlRq", vo.getJlRq()); // 监理日期
            }

        } else {
            projectInfo.put("tensionTime", bankVal);
            projectInfo.put("concreteDesign", bankVal);
            projectInfo.put("concreteStrength", bankVal);
            projectInfo.put("designTension", bankVal);
            projectInfo.put("designExtension", bankVal);
            // 新加字段
            projectInfo.put("jackCode1", bankVal); // 1#张拉千斤顶编号
            projectInfo.put("jackCode2", bankVal); // 2#张拉千斤顶编号
            projectInfo.put("sensorCode1", bankVal); // 1#传感器编号
            projectInfo.put("sensorCode2", bankVal); // 2#传感器编号
            projectInfo.put("zjComments", bankVal); // 自检评语
            projectInfo.put("jlComments", bankVal); // 监理评语
            projectInfo.put("zjRq", bankVal); // 自检日期
            projectInfo.put("jlRq", bankVal); // 监理日期
        }
        // 根据id获取报表编辑信息
        QueryWrapper<ZjTensionReportEdit> wrapper = new QueryWrapper<>();
        wrapper.eq("business_id", params.get("id"));
        ZjTensionReportEdit edit = zjTensionReportEditMapper.selectOne(wrapper);
        if (ObjectUtils.isNotEmpty(edit)) {
            projectInfo.put("gjlq", edit.getGjlq());
            projectInfo.put("gcgg", edit.getGcgg());
            projectInfo.put("temp", edit.getTemp());
            projectInfo.put("dsbfl", edit.getDsbfl());
            projectInfo.put("yb", edit.getYb());
            projectInfo.put("qjd", edit.getQjd());
//            projectInfo.put("bridgeName", edit.getBridgeName());
            projectInfo.put("id", edit.getId());
        } else {
            edit = new ZjTensionReportEdit();
            projectInfo.put("gjlq", edit.getGjlq());
            projectInfo.put("gcgg", edit.getGcgg());
            projectInfo.put("temp", edit.getTemp());
            projectInfo.put("dsbfl", edit.getDsbfl());
            projectInfo.put("yb", edit.getYb());
            projectInfo.put("qjd", edit.getQjd());
//            projectInfo.put("bridgeName", edit.getBridgeName());
            projectInfo.put("id", edit.getId());
        }
        // 返回值规范
        Map<String, Object> result = new HashMap<>();
//        Map<String, Object> mapResult = new HashMap();
//        for (Map<String, Object> map : list) {
//            mapResult.put(map.get("fieldKey").toString(), map.get("fieldVal"));
//        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        mapList.add(projectInfo);
        result.put("data", mapList);
        return result;
    }
}
